#include <QMutex>
#include <QThreadPool>
#include "Thread/RIVIAThreadInterface.h"
#include "Thread/RIVIARunnable.h"

RIVIAThreadInterface* RIVIAThreadInterface::m_pInstance = nullptr;
QMutex RIVIAThreadInterface::m_lockMutex;
QThreadPool RIVIAThreadInterface::m_ThreadPool;
static const int MAX_THREAD_NUM = 8;

RIVIAThreadInterface* RIVIAThreadInterface::getInstance()
{
    if (nullptr == m_pInstance)
    {
        QMutexLocker oLocker(&m_lockMutex);
        {
            if (nullptr == m_pInstance)
            {
                m_pInstance = new RIVIAThreadInterface();
                m_ThreadPool.setMaxThreadCount(MAX_THREAD_NUM);
            }
        }
    }
    return m_pInstance;
}

RIVIAThreadInterface::RIVIAThreadInterface()
{
}

void RIVIAThreadInterface::runFunction(std::function<void(void)> runEntry)
{
    m_ThreadPool.start(new RIVIARunnable(runEntry));
}

void RIVIAThreadInterface::releaseThreads()
{
    m_ThreadPool.waitForDone();
}

void  RUN_FUNCTION_USE_THREAD(std::function<void(void)> runEntry)
{
    RIVIAThreadInterface::getInstance()->runFunction(runEntry);
}
